<template>
  <div class="container">
        <span style="span-size:15px;span-family:'Microsoft YaHei'">
            患者信息查询</span>&nbsp;
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="color:red">*</span>
          <span style="span-size:13px;span-family:'Microsoft YaHei'">病 历 号 :</span>&nbsp;
          <el-input placeholder="病历号" style="width: 110px" again="left" v-model="keywords">
          </el-input>
        </div>
      </el-col>

      <el-col :span="5">
        <div class="grid-content bg-purple">
          <el-button type="primary" style="margin-left: 3px"
                     @click="gosearch"><el-icon><Search /></el-icon> 搜索
          </el-button>
        </div>
      </el-col>
    </el-row>

    <br>
    <span style="span-size:15px;span-family:'Microsoft YaHei'">
            患者信息确认</span>&nbsp;
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <span style="span-size:13px;span-family:'Microsoft YaHei'">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>&nbsp;
          <el-input placeholder="姓名" style="width: 110px" again="left" readonly
                    v-model="info.realname">
          </el-input>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content bg-purple">
          <span style="span-size:13px;span-family:'Microsoft YaHei'">身份证号:</span>
          <el-input placeholder="身份证号" style="width: 180px" readonly
                    v-model="info.idnumber"></el-input>
        </div>
      </el-col>
      <el-col :span="9">
        <div class="grid-content bg-purple">
          <span style="span-size:13px;span-family:'Microsoft YaHei'">家庭住址:</span>
          <el-input placeholder="家庭住址" style="width: 330px" readonly
                    v-model="info.address"></el-input>
        </div>
      </el-col>
    </el-row>
    <!-- :data="categories"  -->
    <el-main class="gao_cate_mana_main">
            <span style="span-size:15px;span-family:'Microsoft YaHei'">
                患者消费信息</span>&nbsp;
      <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange" v-loading="loading">
        <el-table-column
            type="selection"
            width="55" align="left">
        </el-table-column>
        <!-- v-if='false' -->
        <el-table-column
            label="病历号"
            prop="CaseNumber"
            width="120" align="left">
        </el-table-column>
        <el-table-column
            label="项目名称"
            prop="Name"
            width="200" align="left">
        </el-table-column>
        <el-table-column
            label="单价"
            prop="Price"
            width="120" align="left">
        </el-table-column>
        <el-table-column
            label="数量"
            prop="Num"
            width="120" align="left">
        </el-table-column>
        <el-table-column
            label="开立时间"
            prop="CreationTime"
            width="220" align="left">
        </el-table-column>
        <el-table-column
            label="状态"
            prop="State"
            width="120" align="left">
          <template #default="scope">
            <span v-if="scope.row.State==1">已开立未缴费</span>
            <span v-if="scope.row.State==2">已收费未执行</span>
            <span v-if="scope.row.State==3">已执行未完成</span>
            <span v-if="scope.row.State==4">已完成</span>
            <span v-if="scope.row.State==5">已退费</span>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!--:disabled="selItems.length==0" -->
      <el-button type="primary" icon="el-icon-goods"
                 style="margin-top: 10px;width: 100px;"
                 @click="chargeAll" v-if="tableData.length>0">收费结算
      </el-button>

      <el-dialog v-model="chargeDialogFormVisible" title="收费确认" width="500">
        <el-form :model="editForm" label-width="auto"  >
          <el-form-item label="总金额:">
          <span style="font-size: 18px; color: #f56c6c; font-weight: bold">{{ totalAmount }}</span>
          </el-form-item>
          <el-form-item label="确认完成收费吗?">
            <!-- This is just a prompt, no input needed -->
          </el-form-item>
          <el-form-item >
            <el-button type="primary"  @click="charge" >确认</el-button>
            <el-button @click="chargeDialogFormVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </el-main>
  </div>
</template>


<script setup>
import {computed, onMounted, ref} from 'vue'
import service from '@/utils/request'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useCounterStore} from "@/stores/counter.js";

let keywords = ref('')      //要查询的关键字：病历号
let tableData = ref([])     //患者消费信息
let info = ref({realname:'',idnumber:'',address:''})    //患者的确认信息
let chargeDialogFormVisible = ref(false) //收费对话框
// 引入pinia
let counter = useCounterStore()
let idMap = ref([])
//查询
function gosearch(){
  //根据mid（keywords）查询checkapply and price
  service.get("/checkapply/getbymid?mid="+keywords.value).then(
      res=>{
        console.log(res.data)
        tableData.value = res.data.list
        info.value.realname = res.data.info.realname
        info.value.address =  res.data.info.homeaddress
        info.value.idnumber =  res.data.info.idnumber
      }
  )
}
//计算总金额
let totalAmount = computed(() => {
  if (!tableData.value || tableData.value.length === 0) {
    return '0元'
  }
  // 计算总金额（假设 priceMap 存储了每个项目的价格）
  const total = tableData.value.reduce((sum, item) => {
    if(item.State==1){
      const price = item.Price || 0
      return sum + price
    }
  }, 0)
  return `${total}元`
})
//批量收费
function chargeAll(){
  chargeDialogFormVisible.value = true
}
//收费
function charge() {
  // 1. 筛选出所有未收费的项目（状态为1）
  const unchargedItems = tableData.value.filter(item => item.State == 1);

  if (unchargedItems.length === 0) {
    ElMessage.warning('没有选中待收费的项目');
    return;
  }
  // 2. 补充必要字段，准备批量收费数据
  const chargeRequests = unchargedItems.map(item => ({
    registid: item.RegistID,
    invoiceid: item.RegistID,
    itemid: item.ItemID,
    itemtype: 1,
    name: item.Name,
    price: item.Price,
    amount: item.Num,
    deptid: idMap.value[item.DeptName],
    createtime: item.CreationTime,
    createoperid: item.DoctorID,
    paytime: '',
    registerid: counter.vo_user.value.id,
    feetype: 51,
    backid: 0
  }));
  // 4. 显示确认对话框
  ElMessageBox.confirm(
      `确定要收费${chargeRequests.length}个项目吗？总金额：${totalAmount.value},确认后不可修改！`,
      '收费确认',
      {
        confirmButtonText: '确认收费',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false
      }
  ).then(() => {
    // 6. 发送批量收费请求
   return service.post('/patientscost/addbatch', chargeRequests).then(res => {
      if (res.data) {
        return service.get("/checkapply/changebyregistid?registid="+chargeRequests[0].registid).then(res1 => {
          if (res1.data) {
            ElMessage.success(`成功收费${chargeRequests.length}个项目`);
            // 7. 刷新数据
            gosearch();
          } else {
            ElMessage.error('收费失败');
          }
        })
      } else {
        ElMessage.error('收费失败');
      }
    }).finally(() => {
      chargeDialogFormVisible.value = false;
    }).catch(() => {
      // 用户点击了取消
      ElMessage.info('已取消收费操作');
    });
  })
}
onMounted(()=>{
  service.get("/dept/list?depttype=2").then(res=>{
    res.data.forEach((item) => {
      idMap.value[item.deptname] = item.id; // 建立映射
    });
    console.log(idMap.value)
    console.log(idMap.value["医学影像科"])
    console.log(idMap.value["急诊科"])
  })
})
</script>